package utils

import (
	"github.com/golang-jwt/jwt/v4"
	"time"
)

// 定义JWT密钥
var jwtKey = []byte("your_secret_key")

// Claims 定义JWT的Claims
type Claims struct {
	Username string `json:"username"`
	Role     string `json:"role"`
	UserID   uint   `json:"userId"`
	jwt.RegisteredClaims
}

// GenerateToken 生成JWT
func GenerateToken(username, role string, userId uint) (string, error) {
	expirationTime := time.Now().Add(24 * time.Hour)
	claims := &Claims{
		Username: username,
		Role:     role,
		UserID:   userId,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(expirationTime),
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString(jwtKey)
}

// ParseToken 解析JWT
func ParseToken(tokenString string) (string, string, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil || !token.Valid {
		return "", "", err
	}
	return claims.Username, claims.Role, nil
}

// ParseTokenWithID 解析JWT并返回用户ID
func ParseTokenWithID(tokenString string) (string, string, uint, error) {
	claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})
	if err != nil || !token.Valid {
		return "", "", 0, err
	}
	return claims.Username, claims.Role, claims.UserID, nil
}
